package com.thread.threadpool;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.concurrent.*;

/**
 * @author: may
 * @date: 2021年04月16日 22:04
 * 自定义线程池的拒绝策略
 */
public class TestMyRejectedHandler {
    private static Logger logger = LoggerFactory.getLogger(TestMyRejectedHandler.class);

    public static void main(String[] args) {
        ThreadPoolExecutor tpe = new ThreadPoolExecutor(4,
                4,
                0,
                TimeUnit.SECONDS,
                new ArrayBlockingQueue<Runnable>(6),
                Executors.defaultThreadFactory(),
                new MyRejectedHandler());

        for (int i = 0; i < 10; i++) {
            tpe.execute(new MyTask(i));
        }

        System.out.println(tpe);
        System.out.println(tpe.getQueue());

        tpe.execute(new MyTask(100));

        tpe.shutdown();
    }

    static class MyTask implements Runnable {
        private int i;

        public MyTask(int i) {
            this.i = i;
        }

        @Override
        public void run() {
            System.out.println(Thread.currentThread().getName() + " Task" + i);
            try {
                System.in.read();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        @Override
        public String toString() {
            return "MyTask{" +
                    "i=" + i +
                    '}';
        }
    }

    static class MyRejectedHandler implements RejectedExecutionHandler {
        @Override
        public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
            logger.info("对不起，线程池已经满了");
            throw new RejectedExecutionException(r + "is rejected from " + executor);
        }
    }
}
